//
//  FYComposeViewController.swift
//  Mircore
//
//  Created by apple on 16/8/16.
//  Copyright © 2016年 飞羽. All rights reserved.
//

import UIKit


import  SVProgressHUD


//发微博控制器

class FYComposeViewController: UIViewController {
    
    //MARK:-  懒加载控件
    
    //右边按钮
    
    private  lazy  var  rightButton: UIButton = {
        
        let  button  = UIButton()
        
        //添加点击事件
        
        button.addTarget(self, action: #selector(FYComposeViewController.sendAction), forControlEvents: .TouchUpInside)
        
        button.setTitle("发送", forState: .Normal)
        
        button.titleLabel?.font  = UIFont.systemFontOfSize(15)
        
        
        //设置不同状态的文字颜色
        
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        
        //设置不头痛的背景图片
        
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        
        //设置大小
        
        button.size  = CGSize(width: 45, height: 30)
        
        return button
    }()
    
    
    //标题视图
    
    private  lazy var  titleView: UILabel  = {
        
        let  label  = UILabel(fontSize: 17, textColor: UIColor.darkGrayColor())
        
        if  let  name  = FYUserAccountViewModel.sharedUserAccount.userAccount?.name  {
            
            let  result  = "发微博\n\(name)"
            
            //获取名称的range
            
            let range  = (result as  NSString).rangeOfString(name)
            
            
            let attribuedStr  = NSMutableAttributedString(string: result)
            
            
            //添加父文本属性
            
            attribuedStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(14)], range: range)
            
            
            label.attributedText  = attribuedStr
        }else {
            
            
            label.text  = "发微博"
        }
        
        
        
        //多行显示
        
        label.numberOfLines  = 0
        
        label.textAlignment = .Center
        
        label.sizeToFit()
        
        return label
        
    }()
    
    
    //发微博视图
    
    private  lazy  var  textView: FYComposeTextView = {
        
        let  view  = FYComposeTextView()
        
        //设置代理
        
        view.delegate  = self
        
        view.placeHolder = "请输入微博内容"
        
        view.font  = UIFont.systemFontOfSize(16)
        
        //垂直方向开始拖动
        
        view.alwaysBounceVertical  = true
        
        //扩展  不想要纠错工具条的显示
        
        view.autocorrectionType  = .No
        
        return view
        
    }()
    
    //toolbar
    
    private  lazy  var  toolBar: FYComposeToolBar  = {
        
        
        let  composeToolbar = FYComposeToolBar(frame: CGRectZero)
        
        return  composeToolbar
        
    }()
    
    
    
    //配图
    
    private  lazy  var  pictureView: FYComposePictureView = {
        
        let  picVeiw  = FYComposePictureView()
        
        picVeiw.backgroundColor  = self.textView.backgroundColor
        return  picVeiw
    }()
    
    
    //表情键盘
    
    private  lazy  var  emoticonKeyBoard: FYEmoticonKeyBoard = {
    
      let  emoticonKeyBoard = FYEmoticonKeyBoard()
    
      //指定表情键盘大小
        
        emoticonKeyBoard.size  = CGSize(width: self.textView.width, height: 216)
        
        return emoticonKeyBoard
    
    }()
    override  func  viewDidLoad() {
        
        super.viewDidLoad()
        
        setupUI()
    }
    
    
    //添加控件设置约束
    
    private  func  setupUI() {
        
        //监听键盘改变的通知
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FYComposeViewController.keyboardFrameChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        
        //监听点击表情按钮的通知
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FYComposeViewController.didSelectedEmoticon(_:)), name: DidSelectedEmoticonNotification, object: nil)
        
        //监听点击表情按钮的通知
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FYComposeViewController.didSelecteDeleteEmoticon), name: DidSelectedDeleteEmoticonNotification, object: nil)
        
        setupNavUI()
        
        
        //添加控件
        
        view.addSubview(textView)
        
        textView.addSubview(pictureView)
        
        view.addSubview(toolBar)
        
        textView.snp_makeConstraints { (make) in
            
            make.top.equalTo(view)
            
            make.leading.equalTo(view)
            
            make.trailing.equalTo(view)
            
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        
        pictureView.snp_makeConstraints { (make) in
            
            make.top.equalTo(textView).offset(100)
            
            make.centerX.equalTo(textView)
            
            make.width.equalTo(textView.snp_width).offset(-10)
            
            make.height.equalTo(textView.snp_width).offset(-10)
            
        }
        
        toolBar.snp_makeConstraints { (make) in
            
            make.bottom.equalTo(view)
            
            make.leading.equalTo(view)
            
            make.trailing.equalTo(view)
            
            make.height.equalTo(35)
        }
        
        
        //分析处理有循环引用  使用[weak  self]
        
        toolBar.didSelecteToolBarButtonClosure  = {  [weak  self] (type: FYComposeToolBarButtonType) in
            
            
            //根据点击按钮的枚举值进行判断
            
            switch type {
            case .Picture:
                
                self?.didSelectedPicture()
                
            case .Mention:
                
                print("@")
                
            case .Trend:
                
                print("#")
                
            case .Emoticon:
                
                print("表情")
                
                self?.didSelecedEmoticon()
            case .Add:
                
                print("加号")
                
            }
            
        }
        
        //设置配图点击加号的闭包
        
        pictureView.didSeletedAddImageViewClosure = {  [weak  self]  in
        
          self?.didSelectedPicture()
        }
        
    }
    
    
    
    //设置导航栏视图
    
    private  func  setupNavUI() {
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(FYComposeViewController.cancelAction))
        
        navigationItem.rightBarButtonItem  = UIBarButtonItem(customView: rightButton)
        
        //设置右边的按钮不可用
        
        navigationItem.rightBarButtonItem?.enabled  = false
        
        //设置导航栏的自定义titleView
        
        navigationItem.titleView = titleView
        
    }
    
    
    //MARK:-监听点击删除表情按钮的通知方法
    
    @objc  private  func  didSelecteDeleteEmoticon() {
    
    //删除textview内容
        
        textView.deleteBackward()
      
    }
    
    
    //MARK:-  监听点击表情按钮的通知方法
    
    @objc  private  func  didSelectedEmoticon(noti: NSNotification)  {
    
      //获取表情模型
        
        let  emoticon = noti.object  as! FYEmoticon
        
        //插入表情富文本
        
        textView.insertEmoticon(emoticon)
    
    }
    
    
    //MARK:- 监听键盘改变的通知方法
    
    @objc  private  func  keyboardFrameChange(noti: NSNotification) {
        
        
        print(noti.userInfo)
        //获取键盘的frame
        
        let  keyBoardFrame  = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"]  as!  NSValue).CGRectValue()
        
        //获取动画时长
        
        let  duration  = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        
        
        
        //更新约束
        
        toolBar.snp_updateConstraints { (make) in
            
            make.bottom.equalTo(view).offset(keyBoardFrame.origin.y - self.view.height)
        }
        
        //更新约束动画
        
        UIView.animateWithDuration(duration) {
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    //MARK:- 点击事件
    
    @objc  private  func  cancelAction()  {
        
        //取消第一响应者
        
        self.view.endEditing(true)
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc  private  func  sendAction()  {
        
        //判断是否有没有图片  有图片调用上传图片的微博接口
        
        
        if  pictureView.images.count  > 0 {
        
          upload()
         
        }else {
        
          update()
        
        }
 }

    //发送文字微博内容
    
    private  func  update() {
    
    
        //获取微博内容
        
        let  status = textView.emoticonText
        
        
        //获取accesstoken
        
        let  accessToken  = FYUserAccountViewModel.sharedUserAccount.accessToken!
        
         //请求发送微博文字接口
        
        SVProgressHUD.show()
        
        CZNetworkTools.sharedTools.update(accessToken, status: status) { (response, error)  ->()  in
            
            if  error  != nil  {
                
                SVProgressHUD.showErrorWithStatus("网络异常发送失败")
                
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
        
    }
    
  //发送带图片的微博内容
    
    private  func  upload()  {
    
    
        //获取微博内容
        
        let  status = textView.emoticonText
        
        
        //获取accesstoken
        
        let  accessToken  = FYUserAccountViewModel.sharedUserAccount.accessToken!
        
        //获取图片
        
        let  image = pictureView.images.first!
        //请求发送微博文字接口
        
        SVProgressHUD.show()
        
        CZNetworkTools.sharedTools.upload(accessToken, status: status, image: image, callBack: { (response, error)  ->()  in
            
            if  error  != nil  {
                
                SVProgressHUD.showErrorWithStatus("网络异常发送失败")
                
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
        })
        
    }
    
    
    }


//MARK:-  点击toolbar按钮处理逻辑


extension  FYComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate  {
    
    //处理点击表情按钮逻辑
    
    func  didSelecedEmoticon() {
    
        if  textView.inputView == nil {
        
        //设置自定义表情键盘
            
        textView.inputView  =  emoticonKeyBoard
            
            toolBar.switchEmotionIcon(true)
        
        }else {
        
        //设置系统键盘
            
            textView.inputView  = nil
        
          toolBar.switchEmotionIcon(false)
        }
        
       //设置其为第一响应者
        
        textView.becomeFirstResponder()
        
        //重写刷新inputview
        
        textView.reloadInputViews()
    
    }
    
    
    
     //处理点击图片逻辑
    
    func   didSelectedPicture() {
        
        let  picCtr  = UIImagePickerController()
        
        picCtr.delegate  = self
        
        
        if  UIImagePickerController.isSourceTypeAvailable(.Camera) {
            
            //设置来源类型
            
            picCtr.sourceType  = .Camera
            
        }else  {
            
            //设置图库
            
            picCtr.sourceType  = .PhotoLibrary
            
        }
        
        //判断前置摄像头是否可用
        
        
        if  UIImagePickerController.isCameraDeviceAvailable(.Front) {
            
            
            print("前置摄像头可用")
            
        }else  if  UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            
            
            print("后置摄像头可用")
        }else  {
            
            print("没有摄像头")
            
        }
        
        //是否允许编辑
        
        //        picCtr.allowsEditing  = true
        
        presentViewController(picCtr, animated: true, completion: nil)
        
    }
    
    //MARK:-  UIImagePickerControllerDelegate 实现代理方法   如果实现了代理方法直接调用dismis操作
    
    func  imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        
        let  scaleImage = image.ScaleImageWithScaleWidth(200)
        
        
//        let  data = UIImageJPEGRepresentation(scaleImage, 0.5)
        
//        data?.writeToFile("/Users/apple/Desktop/1.png", atomically: true)
        
        
        
        //添加配图信息
        
        pictureView.addImage(scaleImage)
        
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func  imagePickerControllerDidCancel(picker: UIImagePickerController) {
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
}


//MARK:-  实现UITextViewDelegate代理方法

extension  FYComposeViewController: UITextViewDelegate  {
    
    
    //内容改变
    
    func  textViewDidChange(textView: UITextView) {
        
        
        //如果有内容则右侧按钮可用 否则不可用
        
        navigationItem.rightBarButtonItem?.enabled  = textView.hasText()
        
    }
    
    //将要拖动的时候让其失去第一响应者
    
    func  scrollViewWillBeginDragging(scrollView: UIScrollView) {
        
        //失去第一响应者
        
        self.view.endEditing(true)
    }
}
